package servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import entity.CartItem;
import entity.ShoppingCart;

/**
 * Servlet implementation class ShoppingCarEditCountServlet
 */
@WebServlet("/ShoppingCarEditCount.html")
public class ShoppingCarEditCountServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("进入Servlet");
		String rIdStr = request.getParameter("rateId");
		int rateId=0;
		if(rIdStr!=null&&!rIdStr.isEmpty()){
			rateId=Integer.valueOf(rIdStr);
			ShoppingCart cart = (ShoppingCart)request.getSession().getAttribute("shoppingCarList");
			String type = request.getParameter("type");
			if(type!=null&&!type.isEmpty()){
				for (CartItem cartItem : cart.getCartItemList()) {
					if(cartItem.getRate().getRateId()==rateId){
						if("add".equals(type)){
							cartItem.setCount(cartItem.getCount()+1);
							cartItem.setUnitPrice(cartItem.getUnitPrice());
							System.out.println(cartItem.getUnitPrice());
						}else if("minus".equals(type)){
							if(cartItem.getCount()>1){
								cartItem.setCount(cartItem.getCount()-1);
								cartItem.setUnitPrice(cartItem.getUnitPrice());
							}
						}
						break;
					}
				}
				request.getSession().setAttribute("shoppingCarList", cart);
			}
		}
		
		ShoppingCart cart = (ShoppingCart)request.getSession().getAttribute("shoppingCarList");
		for (CartItem cartItem : cart.getCartItemList()) {
			if(cartItem.getRate().getRateId()==rateId){
				System.out.println(cartItem.getCount());
				break;
			}
		}
//		response.sendRedirect(request.getHeader("referer"));
		/*System.out.println(request.getHeader("referer"));*/
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
